<script setup lang="ts">
import { ref,reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage} from 'element-plus'
import { menuListService,updateMenuService } from "@/api/menu";
import { roleMenuListService } from "@/api/role"
import {InitData} from "@/type/menu" 
//导入设置token的函数
import { useTokenStore } from '@/stores/token'

//从当前路由参数中获取角色id
const route = useRoute();
const query: any = route.query;
const roleId = ref(query.id)

const defaultProps = {
    children: 'children',
    label: 'name',
}
//调用后台接口查询角色id对应的权限集合
const menus = ref([])
const roleMenuList = async () => {
    let params = {
        roleId: roleId.value
    }
    let result = await roleMenuListService(params)
    menus.value = result.data
}
roleMenuList();
//ref<any>类型赋值给reactive<>解决办法：toRefs
//const menusReactive = reactive(toRefs(menus.value))
const menu = reactive(new InitData())
//调用后台接口查询权限树
const menuList = async () => {
    let result = await menuListService()
    menu.list = result.data
}
menuList();
const treeRef = ref()
const router = useRouter()
const tokenStore = useTokenStore();
//修改权限按钮事件
const updateMenus = async() => {
    let list = treeRef.value.getCheckedKeys().sort(function(a:number,b:number){return a-b});
    let params = {
        roleId: roleId.value,
        list: list
    }
    let result = await updateMenuService(params) as any
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //设置token值
    tokenStore.setToken(result.data)
    router.push('/admin/role')
} 
const returnRoleView = () => {
    router.push('/admin/role')
} 
</script>

<template>
    <!-- 权限树形控件 -->
    <div>
        <el-tree 
        ref="treeRef"
        :data="menu.list" 
        show-checkbox
        node-key="id"
        :check-strictly="true" 
        :default-checked-keys="menus" 
        :props="defaultProps" 
        />
        <el-button type="primary" @click="updateMenus">修改权限</el-button>
        <el-button type="primary" @click="returnRoleView">返回</el-button>
    </div>
</template>

<style lang="scss" scoped></style>